#!/usr/bin/env bash

set -e

export DOCKER_REPO_URL=https://download.docker.com/linux/centos/docker-ce.repo
export K8S_REPO_URL=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
export K8S_REPO_KEY="https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg"
export POD_NET_START=10.244.0
export POD_IMG_REGISTRY=registry.aliyuncs.com/google_containers
export FLANNEL_CONF_URL=https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml


check_succeed()
{
    if [ $? -eq 0 ];then
        echo "Succeed!"
	echo ""
    else
        echo "Faild!"
	echo ""
        exit
    fi
}

# disable firewalld
disable_firewall()
{
    echo "disable firewalld ..."
    sudo service firewalld stop
    check_succeed
    echo "disable firewalld service ..."
    systemctl disable firewalld.service
    check_succeed
}

# disable selinux
disable_selinux()
{
    echo "disable selinux ..."
    sudo sed -i 's/^SELINUX=enforcing$/SELINUX=permissive/' /etc/selinux/config
}

# disable swap
disable_swap()
{
    echo "disable swap ..."
    sudo swapoff -a
    check_succeed
    sed -ri '/\sswap\s/s/^#?/#/' /etc/fstab
}

modprobe_br_netfilter()
{
    echo "modprobe br_netfilter ..."
    modprobe br_netfilter
    check_succeed
    echo "br_netfilter" > /etc/modules-load.d/br_netfilter.conf
}


modprobe_vhost()
{
    echo "modprobe vhost-vsock ..."
    modprobe vhost-vsock
    check_succeed
    echo "modprobe vhost-net ..."
    modprobe vhost-net
    check_succeed
    echo "vhost-vsock vhost-net" > /etc/modules-load.d/vhost.conf
}

# enable iptables check the net bridge traffic
enable_check_br_traffic()
{
    modprobe_br_netfilter

cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
    check_succeed

    sudo sysctl --system
    check_succeed
}

# install dependency
install_deps()
{
    echo "install dependency packages ..."
    sudo yum install -y yum-utils
    check_succeed
}

# install docker
install_docker()
{
    echo "install docker ..."
    sudo yum-config-manager --add-repo ${DOCKER_REPO_URL}
    sudo yum install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin --allowerasing
    check_succeed
}

install_kata-containers()
{
    echo "install kata-containers ..."
    REMOTE_PATH=/hygon-devkit/4.0/2025-01-01/csv/confidential-containers/RPMs
    FILE_NAME=kata-containers-0.5.0-1.x86_64.rpm
    LOCAL_DIR=RPMs
    mkdir -p "$LOCAL_DIR"
    echo $LOCAL_DIR/$FILE_NAME
    # If the directory don't have the rpm file, download it
    if [ -z "$(ls -A "$LOCAL_DIR"/$FILE_NAME 2>/dev/null)" ] ; then
        ./../../tools/sftp download $REMOTE_PATH/$FILE_NAME ./$LOCAL_DIR/$FILE_NAME
    fi
    sudo rpm -ivh --nodeps RPMs/kata-containers-0.5.0-1.x86_64.rpm 
    check_succeed
}

install_hag()
{
    echo "install hag ..."
    sudo ./../../common/install/install_hag.sh
    check_succeed
}

import_export_certs()
{
    echo "import HGSC ..."
    sudo /opt/hygon/bin/hag general hgsc_import
    check_succeed
    echo "export cert chain ..."
    mkdir -p /opt/csv
    /opt/hygon/bin/hag csv export_cert_chain
    cat pdh.cert pek.cert oca.cert cek.cert hsk.cert hrk.cert  > cert_chain.cert
    mv cert_chain.cert /opt/csv/
    check_succeed
}

install_simple-kbs()
{
    echo "install simple-kbs ..."
    REMOTE_PATH=/hygon-devkit/4.0/2025-01-01/csv/confidential-containers/RPMs
    FILE_NAME=simple-kbs-0.5.0-1.x86_64.rpm
    LOCAL_DIR=RPMs
    mkdir -p "$LOCAL_DIR"
    echo $LOCAL_DIR/$FILE_NAME
    # If the directory don't have the rpm file, download it
    if [ -z "$(ls -A "$LOCAL_DIR"/$FILE_NAME 2>/dev/null)" ] ; then
        ./../../tools/sftp download $REMOTE_PATH/$FILE_NAME ./$LOCAL_DIR/$FILE_NAME
    fi
    sudo rpm -ivh --nodeps RPMs/simple-kbs-0.5.0-1.x86_64.rpm
    check_succeed
}

# start docker service
start_docker_service()
{
    echo "start containerd service ..."
    sudo systemctl enable --now docker
    sudo systemctl daemon-reload
    sudo service docker restart
    check_succeed
}

config_containerd()
{
    containerd config default > /etc/containerd/config.toml
    sed -i 's#registry.k8s.io/pause:3.6#registry.cn-hangzhou.aliyuncs.com/google_containers/pause:3.6#g' /etc/containerd/config.toml
    check_succeed
}

enable_kata_runtime_for_containerd()
{
cat >>/etc/containerd/config.toml<<EOF
[plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata]
  cri_handler = ""
  runtime_type = "io.containerd.kata.v2"
  privileged_without_host_devices = true
  pod_annotations = ["io.katacontainers.*"]
  [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata.options]
    ConfigPath = "/opt/confidential-containers/share/defaults/kata-containers/configuration.toml"
[plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata-qemu]
  cri_handler = "cc"
  runtime_type = "io.containerd.kata.v2"
  privileged_without_host_devices = true
  pod_annotations = ["io.katacontainers.*"]
  [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata-qemu.options]
    ConfigPath = "/opt/confidential-containers/share/defaults/kata-containers/configuration-qemu.toml"
[plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata-qemu-csv]
  cri_handler = "cc"
  runtime_type = "io.containerd.kata.v2"
  privileged_without_host_devices = true
  pod_annotations = ["io.katacontainers.*"]
  [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata-qemu-csv.options]
    ConfigPath = "/opt/confidential-containers/share/defaults/kata-containers/configuration-qemu-csv.toml"
EOF
}

# start containerd service
start_containerd_service()
{
    echo "start containerd service ..."
    sudo systemctl enable --now containerd
    sudo systemctl daemon-reload
    sudo service containerd restart
    check_succeed
}

# install K8S
install_K8S()
{
    echo "install K8S ..."
cat <<EOF | sudo tee /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=${K8S_REPO_URL}
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=${K8S_REPO_KEY}
EOF

    check_succeed

    sudo yum install -y kubelet kubeadm kubectl --disableexcludes=kubernetes
    check_succeed
}

# configure K8S
configure_K8S()
{
    echo "configure K8S ..."
cat << EOF | sudo tee  /usr/lib/systemd/system/kubelet.service.d/0-containerd.conf
[Service]                                                 
Environment="KUBELET_EXTRA_ARGS=--container-runtime=remote --runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock"
EOF
    check_succeed
}

# initialize K8S
init_K8S()
{
    echo "initialize K8S ..."
    sudo kubeadm init --cri-socket /run/containerd/containerd.sock --pod-network-cidr=${POD_NET_START}.0/16 --image-repository ${POD_IMG_REGISTRY}
    rm -rf $HOME/.kube
    mkdir -p $HOME/.kube
    sudo /bin/cp -f /etc/kubernetes/admin.conf $HOME/.kube/config
    sudo chown $(id -u):$(id -g) $HOME/.kube/config
    check_succeed
}

# enable master node
enable_master_node()
{
    echo "enable master node ..."
    su -c \
    'export KUBECONFIG=/etc/kubernetes/admin.conf
    kubectl taint nodes --all node-role.kubernetes.io/control-plane-'
    check_succeed
}

# install flannel
install_flannel()
{
    echo "get flannel config"
    su -c \
    "wget --no-check-certificate --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=0 ${FLANNEL_CONF_URL}  -O kube-flannel.yml"
    check_succeed

    echo "install flannel ..."
    su -c \
        "export KUBECONFIG=/etc/kubernetes/admin.conf
        kubectl apply -f ./kube-flannel.yml"
    check_succeed

    # wait the flannel ready
    sleep 10
}

# create kata RuntimeClass
create_kata_RuntimeClass()
{
    echo "create kata RuntimeClass ..."
su -c \
"export KUBECONFIG=/etc/kubernetes/admin.conf
cat <<-EOF | kubectl apply -f -
apiVersion: node.k8s.io/v1
kind: RuntimeClass
metadata:
  name: kata
handler: kata
EOF

cat <<-EOF | kubectl apply -f -
apiVersion: node.k8s.io/v1
kind: RuntimeClass
metadata:
  name: kata-qemu
handler: kata-qemu
EOF

cat <<-EOF | kubectl apply -f -
apiVersion: node.k8s.io/v1
kind: RuntimeClass
metadata:
  name: kata-qemu-csv
handler: kata-qemu-csv
EOF"
    check_succeed
}

if [ $UID -ne 0 ]; then
    echo "please use root priviledge!!!"
    exit
fi

# 1. permissions settings
disable_firewall
disable_selinux
disable_swap
enable_check_br_traffic
modprobe_vhost

# 2. install packages
install_deps
install_docker
install_kata-containers
install_hag
import_export_certs
install_simple-kbs
config_containerd
enable_kata_runtime_for_containerd
install_K8S
configure_K8S

# 3. start services
start_docker_service
start_containerd_service

# 4. initial system
init_K8S
enable_master_node
install_flannel
create_kata_RuntimeClass

echo "The CSV containers environment setting done!"
